package com.hbplat.shardingsphere.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 接口请求
 */
public class PostHttpApiUtil {

    private static String httpUrl = "http://sms.m1n.cn/sms.aspx";

    private static String userId = "1661";

    private static String userName = "51eliao";

    private static String passwords = "51eliao";

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(PostHttpApiUtil.class);

    private static DefaultProfile profile = null;
    private static IAcsClient client = null;

    static {
        profile = DefaultProfile.getProfile("cn-hangzhou", "LTAIKY0j9l7kZugh", "uxiE3rjQyK4E5SapobbsJLls3QUgBi");
        client = new DefaultAcsClient(profile);
    }



    public static void sendAliyunMessage( String phoneNumbers,String templateCode, String templateParam){
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", "51医疗");
        request.putQueryParameter("TemplateCode", templateCode);
        if(StringUtil.isNotEmpty(templateParam)){
            request.putQueryParameter("TemplateParam", templateParam);
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            logger.info(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }


    /**
     * 短信发送接口
     * @param message
     * @param phoneNumber 多个号码用英文逗号分隔
     */
    public static void httpURLConnectionPOST (String message,
                                              String phoneNumber, String sendTimes) {
        if(null == sendTimes){
            sendTimes = "";
        }
        if(StringUtil.isEmpty(phoneNumber)){
            return;
        }
        try {
            URL url = new URL(httpUrl);

            // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)
            // 此时cnnection只是为一个连接对象,待连接中
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
            connection.setDoOutput(true);

            // 设置连接输入流为true
            connection.setDoInput(true);

            // 设置请求方式为post
            connection.setRequestMethod("POST");

            // post请求缓存设为false
            connection.setUseCaches(false);

            // 设置该HttpURLConnection实例是否自动执行重定向
            connection.setInstanceFollowRedirects(true);

            // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
            // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据
            // ;charset=utf-8 必须要，不然妙兜那边会出现乱码【★★★★★】
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            connection.connect();

            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());

            String action = "action="+ URLEncoder.encode("send", "utf-8");
            String userid = "&userid="+ URLEncoder.encode(userId, "utf-8");
            String account = "&account="+ URLEncoder.encode(userName, "utf-8");
            String password = "&password="+ URLEncoder.encode(passwords, "utf-8");
            String mobile = "&mobile="+ URLEncoder.encode(phoneNumber, "utf-8");
            String content = "&content="+ URLEncoder.encode(message, "utf-8");
            if(StringUtil.isNotEmpty(sendTimes)){
                sendTimes = "&sendTime="+ URLEncoder.encode(sendTimes, "utf-8");//空为及时
            }
            //String extno = "&extno="+ URLEncoder.encode("", "utf-8");
            // 格式 parm = aaa=111&bbb=222&ccc=333&ddd=444
            String parm = action+ userid+ account+ password+ mobile+ content+ sendTimes;

            // 将参数输出到连接
            dataout.writeBytes(parm);

            // 输出完成后刷新并关闭流
            dataout.flush();
            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)

//            System.out.println(connection.getResponseCode());

            // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder(); // 用来存储响应数据

            // 循环读取流,若不到结尾处
            while ((line = bf.readLine()) != null) {
//                sb.append(bf.readLine());
                sb.append(line).append(System.getProperty("line.separator"));
            }
            bf.close();    // 重要且易忽略步骤 (关闭流,切记!)
            connection.disconnect(); // 销毁连接
            logger.info(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 单个用户消息发送
     * @param paramMap
     * @param messgae
     */
    public static void sendMessgae(Map paramMap, String messgae){
        if(null != paramMap){
            String phone = StringUtil.valueOfString(paramMap.get("phone"));
            String phone2 = StringUtil.valueOfString(paramMap.get("phone2"));
            if(phone.equals(phone2)){
                //号码相同则只发一次
                if(StringUtil.isNotEmpty(phone)){
                    httpURLConnectionPOST(messgae,phone,"");
                }
            }else{
                //不同号码发送二次
                httpURLConnectionPOST(messgae,phone+","+phone2,"");
            }
        }
    }
    
}
